package 树;
/**
 * https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 */
public class _105_从前序与中序遍历序列构造二叉树 {
    public class TreeNode {
        int val;
       TreeNode left;
       TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val,TreeNode left,TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder,0, preorder.length-1,inorder,
                0, inorder.length-1);
    }

    /*
       若前序遍历数组为 preorder[preStart..preEnd]，
       中序遍历数组为 inorder[inStart..inEnd]，
       构造二叉树，返回该二叉树的根节点
    */
    private TreeNode build(int[] preorder,int preStart,int preEnd,
                           int[] inorder,int inStart,int inEnd){
        if(preStart > preEnd) return null;
        int rooVal = preorder[preStart]; //前序遍历中根节点的值为第一个元素
        int index = -1;//记录中序遍历中，根节点所在的索引
        for(int i=inStart;i<=inEnd;++i){
            if(rooVal == inorder[i]){
                index = i;
                break;
            }
        }
        //可以在中序遍历中计算出左子树的个数，
        int leftSize = index - inStart;

        //构造根节点
        TreeNode root = new TreeNode(rooVal);
        //递归的在左子树和右子树构造根节点，控制好数组的索引
        root.left = build(preorder,preStart+1,preStart + leftSize,
                          inorder,inStart,index-1);
        root.right = build(preorder,preStart+leftSize+1,preEnd,
                           inorder,index+1,inEnd);

        return root;
    }

    private TreeNode build2(int[] preorder,int preStart,int preEnd,
                           int[] inorder,int inStart,int inEnd){
        if(preStart > preEnd){
            return null;
        }
        int rootVal = preorder[preStart];
        int index = -1;
        for(int i=inStart;i<=inEnd;++i){
            if(rootVal == inorder[i]){
                index = i;
                break;
            }
        }
        int leftSize = index - inStart;
        TreeNode root = new TreeNode(rootVal);

        root.left = build2(preorder,preStart+1,preStart+leftSize,
                          inorder,inStart,index-1);

        root.right = build2(preorder,preStart+leftSize+1,preEnd,
                           inorder,index+1,inEnd);

        return root;
    }
}
